package com.lin.controller;

import com.lin.VO.ResultVO;
import com.lin.dataobject.SellerInfo;
import com.lin.enums.ResultEnum;
import com.lin.exception.SellException;
import com.lin.form.SellerUserForm;
import com.lin.server.SellerService;
import com.lin.utils.KeyUtils;
import com.lin.utils.MD5SaltUtils;
import com.lin.utils.ResultVOUtils;
import com.lin.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 卖家用户
 * 2017-07-30 15:28
 */
@Controller
@RequestMapping("/user")
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

//    @Autowired
//    private StringRedisTemplate redisTemplate;

//    @Autowired
//    private ProjectUrlConfig projectUrlConfig;

//    @RequestMapping(path = "/login",method= RequestMethod.POST)
//    public ModelAndView login(@RequestParam("openid") String openid,
//                              HttpServletResponse response,
//                              Map<String, Object> map) {
//
//        //1. openid去和数据库里的数据匹配
//        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
//        if (sellerInfo == null) {
//            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
//            map.put("url", "/sell/seller/order/list");
//            return new ModelAndView("common/error");
//        }
//
//        //2. 设置token至redis
//        String token = UUID.randomUUID().toString();
//        Integer expire = RedisConstant.EXPIRE;
//
//        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);
//
//        //3. 设置token至cookie
//        CookieUtil.set(response, CookieConstant.TOKEN, token, expire);
//        System.out.println(projectUrlConfig.getSell() + "/sell/seller/order/list");
//        return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");
//
//    }
//
//    @RequestMapping("/logout")
//    public ModelAndView logout(HttpServletRequest request,
//                               HttpServletResponse response,
//                               Map<String, Object> map) {
//        //1. 从cookie里查询
//        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
//        if (cookie != null) {
//            //2. 清除redis
//            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
//
//            //3. 清除cookie
//            CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
//        }
//
//        map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
//        map.put("url", "/sell/seller/order/list");
//        return new ModelAndView("common/success", map);
//    }
//
//    @GetMapping("/goMain")
//    public ModelAndView goMain(){
//        return new ModelAndView("index/index1");
//    }

    @RequestMapping("/list")
    public ModelAndView list(){
        return new ModelAndView("user/index1");
    }
    @ResponseBody
    @RequestMapping("/getData")
    public Map<String,Object> getData(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "rows", defaultValue = "10") Integer rows,
                                      HttpServletRequest request) {
        PageRequest request1=new PageRequest(page-1,rows);
        String username=request.getParameter("username");
        String startTime=request.getParameter("startTime");
        String endTime=request.getParameter("endTime");
        Page<SellerInfo> sellerInfos=sellerService.findAll(username,startTime,endTime,request1);
        Map<String,Object> map=new HashMap<>();
        map.put("rows",sellerInfos.getContent());
        map.put("total",sellerService.getSize(username,startTime,endTime));
        return map;
    }

    @RequestMapping("/view")
    public ModelAndView addView(@RequestParam(value = "id",required = false) String id,
                                Map<String,Object> map){
        if (StringUtils.isNotEmpty(id)){
            SellerInfo sellerInfo=sellerService.findUserById(id);
            map.put("user",sellerInfo);
        }
        return new ModelAndView("user/add_view");
    }

    @ResponseBody
    @PostMapping("/save")
    public ResultVO save(@Valid SellerUserForm form, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultVOUtils.error(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        SellerInfo sellerInfo=new SellerInfo();
        try{
            if (StringUtils.isNotEmpty(form.getSellerId())){
                sellerInfo=sellerService.findUserById(form.getSellerId());
            }
            else{
                if (sellerService.findByUserName(form.getUsername())!=null){
                    return ResultVOUtils.error(ResultEnum.USERNAME_EXISTS.getCode(),ResultEnum.USERNAME_EXISTS.getMessage());
                }
                form.setSellerId(KeyUtils.getUniqueKey());
            }
            form.setPassword(MD5SaltUtils.getEncryptedPwd(form.getPassword()));
            BeanUtils.copyProperties(form,sellerInfo);
            sellerService.save(sellerInfo);
        }catch (SellException e){
            return ResultVOUtils.error(ResultEnum.SAVE_ERROR.getCode(),
                    ResultEnum.SAVE_ERROR.getMessage());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ResultVOUtils.success("保存成功");
    }

    @ResponseBody
    @PostMapping("del")
    public ResultVO del(@RequestParam(value = "id",required = true) String id){
        SellerInfo sellerInfo=sellerService.findUserById(id);
        if (sellerInfo==null){
            return ResultVOUtils.error(ResultEnum.NO_FOUND.getCode(),
                    ResultEnum.NO_FOUND.getMessage());
        }
        sellerService.del(sellerInfo);
        return ResultVOUtils.success("删除成功");
    }

    @ResponseBody
    @PostMapping("review")
    public ResultVO review(@RequestParam(value = "id",required = true) String id){
        SellerInfo sellerInfo=sellerService.findUserById(id);
        if (sellerInfo==null){
            return ResultVOUtils.error(ResultEnum.NO_FOUND.getCode(),
                    ResultEnum.NO_FOUND.getMessage());
        }
        sellerInfo.setStatus(1);
        sellerService.save(sellerInfo);
        return ResultVOUtils.success("审核成功");
    }
}
